package team.bluepen.supermarket.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import team.bluepen.supermarket.conf.KafkaProperties;
import team.bluepen.supermarket.data.entity.ProductNameAmount;
import team.bluepen.supermarket.kafka.KafkaReceiveCallback;
import team.bluepen.supermarket.kafka.KafkaReceiver;
import team.bluepen.supermarket.kafka.KafkaTopics;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Receive amount of product's name.
 *
 * @author RollW
 */
@Service
public class ProductNameReceiveService implements KafkaReceiveCallback<ProductNameAmount> {
    private static final Logger log = LoggerFactory.getLogger(ProductNameReceiveService.class);
    private final KafkaReceiver<ProductNameAmount> receiver;
    private final Map<String, Integer> productNameAmountMap = new HashMap<>();
    private final Map<String, ProductNameAmount> amountMap = new HashMap<>();

    public ProductNameReceiveService(KafkaProperties kafkaProperties) {
        receiver = new KafkaReceiver<>(
                KafkaTopics.STATE_DATA_TOPIC,
                kafkaProperties.getBootstrapServers(),
                "ProductNameRecvServ",
                DataKeys.PRODUCT_NAME_COUNT,
                ProductNameAmount.deserializer(),
                this);
       receiver.start();
    }

    public Map<String, Integer> getProductNameAmountMap() {
        return productNameAmountMap;
    }

    public void close() {
        receiver.close();
    }

    public Collection<ProductNameAmount> getAmounts() {
        return amountMap.values();
    }

    @Override
    public void onReceive(ProductNameAmount data) {
        amountMap.put(data.getName(), data);
        productNameAmountMap.put(data.getName(), data.getAmount());
    }
}
